/**
 * 基础菜单 商品管理
 */
<template>
<!--  <div class="alert-box-item">-->
<!--    <div class="bigImg-div" @click="toGetImg">-->
<!--      <img class="bigImg" :src=valueUrl v-if="valueUrl">-->
<!--    </div>-->
<!--  </div>-->

  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.searchName" placeholder="输入商品名称"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button type="danger" @click="batchDel()" plain>批量删除</el-button>

      </el-form-item>



    </el-form>
    <!--列表-->
    <el-table size="small" @select="checkSelect" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="goodsName" label="商品名称" width="150" align="center">
      </el-table-column>
      <el-table-column sortable prop="goodsPrice" label="商品价格" width="150" align="center">
      </el-table-column>
      <el-table-column sortable prop="editTime" label="修改时间" width="200" align="center">

        <template slot-scope="scope">
          <div>{{scope.row.editTime|timestampToTime}}</div>
        </template>

      </el-table-column >

      <el-table-column sortable prop="editUser" label="修改人" width="150" align="center">
      </el-table-column>


      <el-table-column sortable prop="url" label="图片展示" width="250" align="center">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src= "require('../../../image/'+scope.row.id+'/'+scope.row.url)"
            :preview-src-list="setUrl(scope.row)">
          </el-image>

        </template>
      </el-table-column>



      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="goodsDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <!-- 编辑界面 -->
    <el-dialog :title="editForm.title" :visible.sync="editFormVisible" width="40%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">

        <el-form-item label="商品id" prop="goodsId">
          <el-input size="small" type="text" v-model="editForm.goodsId" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input size="small" v-model="editForm.goodsName" auto-complete="off" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input size="small" v-model="editForm.goodsPrice" auto-complete="off" placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload ref="my-upload"
            class="upload-demo"
            drag
            :action="upLoadImg()"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {GoodsList, GoodsSave, GoodsDelete, GoodsImgSave} from '../../api/basisMG'
import Pagination from '../../components/Pagination'
import {lert} from "../../api/axiosFun";
import { playVoice } from '../../api/voice';

let inputElement = null

export default {
  data() {
    return {
      num: 9,
      img: "guihua11686334283978.png",
      imgs: [],
      // 实例化一个音频播放器对象
      audio: new Audio(),
      audio1: require('../../assets/audio/audio1.mp3'),
      audio2: require('../../assets/audio/audio2.mp3'),

      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      ids: '',
      editForm: {
        title: '添加',
        goodsId: '',
        goodsName: '',
        goodsPrice: '',
        token: localStorage.getItem('username')
      },
      // rules表单验证
      rules: {
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
      },
      checkedBrands:[],
      formInline: {
        page: 1,
        limit: 10,
        searchName:'',
        varLable: '',
        varName: '',
        username: localStorage.getItem('username')
      },
      // 删除商品
      seletedata: {
        ids: '',
        // token: localStorage.getItem('logintoken')
      },
      listData: [], //商品数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  // created() {mounted
  mounted() {
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {

    clearFiles () {
      this.$refs['my-upload'].clearFiles();
    },

    setUrl(row) {
      var res = [];
      var list=row.srcList
      for (let i = 0; i < list.length ; i++) {
        res.push(require('../../../image/'+row.id+'/'+list[i]))
      }
      return res
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file)
    },
    upLoadImg:function() {
      return "/api/Goods/img?token=" + localStorage.getItem('token') + "&id=" + this.editForm.goodsId
      // GoodsImgSave()
      //   .then(res => {
      //     console.log(res)
      //     if (res.success) {
      //       this.$message.success('图片上传成功!')
      //     } else {
      //       this.$message.error('图片上传失败，请稍后再试！')
      //
      //     }
      //   })
      //   .catch(err => {
      //     this.$message.error('图片上传出错，请稍后再试！')
      //   })
    },

    // 获取商品列表
    getdata(parameter) {

      this.loading = true
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      GoodsList(parameter)
        .then(res => {
          lert(res);

          const r = JSON.parse(res.data);
          this.loading = false
          if (res.success == false) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            // 开启自动播放
            // this.audio.autoplay = true;
            // this.audio.src = this.audio1;
            playVoice("获取列表成功")
            this.listData = r.records
            // console.log(this.listData)
            // for (const item in this.listData.srcList) {
            //   imgs.append(require('../../../image/' + item.id + '/' + item))
            // }

            // 分页赋值
            this.pageparm.currentPage = r.current
            this.pageparm.pageSize = r.size
            this.pageparm.total = r.total
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('菜单加载失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parameter) {
      this.formInline.page = parameter.currentPage
      this.formInline.limit = parameter.pageSize
      console.log("分页分页")
      this.getdata(this.formInline)
    },

    batchDel() {
      var _this = this;
      for (let i = 0; i < _this.checkedBrands.length; i++) {
        if (i == 0) {
          this.ids += _this.checkedBrands[i].id;
        } else {
          this.ids += ',';
          this.ids += _this.checkedBrands[i].id;
        }
      }

      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          GoodsDelete(_this.ids)
            .then(res => {
              lert(res);
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '商品信息已删除!'
                })
                this.loading = false
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
              _this.ids = [];
            })
            .catch(err => {
              this.$message.error('商品信息删除失败，请稍后再试！')
            })
        })
    },
    //选择此商品事件
    checkSelect(data) {
      this.checkedBrands = data;
    },
    // 搜索事件
    search() {
      this.getdata(this.formInline)
    },

    //显示编辑界面
    handleEdit: function (index, row) {

      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.editForm.title = '修改'
        this.editForm.goodsId = row.id
        this.editForm.goodsName = row.goodsName
        this.editForm.goodsPrice = row.goodsPrice

      } else {
        this.editForm.title = '添加'
        this.editForm.goodsId = ''
        this.editForm.goodsName = ''
        this.editForm.goodsPrice = ''
      }
    },

    // 编辑、增加页面保存方法
    submitForm(editData) {

      this.$refs[editData].validate(valid => {
        if (valid) {

          GoodsSave(this.editForm)
            .then(res => {
              lert(res);

              this.editFormVisible = false
              this.loading = false
              if (res.success) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '商品信息保存成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('商品信息保存失败，请稍后再试！')
            })
        } else {
          return false
        }
      })
    },
    // 删除商品
    goodsDelete(row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          GoodsDelete(row.id)
            .then(res => {
              lert(res);
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '商品信息已删除!'
                })
                this.loading = false
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.$message.error('商品信息删除失败，请稍后再试！')
            })
        })
      // .catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消删除'
      //   })
      // })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>


